package com.ipfsemc.ipfsemc.service.imp;

import com.ipfsemc.ipfsemc.mapper.HashrateMapper;
import com.ipfsemc.ipfsemc.mapper.SpaceHashrateMapper;
import com.ipfsemc.ipfsemc.mapper.UserSpaceMapper;
import com.ipfsemc.ipfsemc.model.Hashrate;
import com.ipfsemc.ipfsemc.model.SpaceHashrate;
import com.ipfsemc.ipfsemc.model.UserSpace;
import com.ipfsemc.ipfsemc.model.UserSpaceVo;
import com.ipfsemc.ipfsemc.service.IHashrateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class HashrateServiceImpl implements IHashrateService {
    @Autowired
    private HashrateMapper hashrateMapper;

    @Autowired
    private SpaceHashrateMapper spaceHashrateMapper;

    @Autowired
    private UserSpaceMapper userSpaceMapper;

    @Override
    public int add(Hashrate hashrate) {
        java.sql.Date timePara = null;
        try {
            timePara = new java.sql.Date(System.currentTimeMillis());
            hashrate.setHashrateTime(timePara);//这个参数实际上是要那边接口传过来的

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(hashrate.getHashrateTime());
            calendar.add(Calendar.DATE, -1);


            timePara = new java.sql.Date(calendar.getTimeInMillis());
//            根据昨天的记录查询总算力、矿池总量
            Hashrate h = hashrateMapper.selectByLastTime(timePara);

            BigDecimal aver = new BigDecimal((hashrate.getHashrateAdd() - h.getHashrateAdd())*1.0 / hashrate.getMillTotal()*1.0);
            hashrate.setAverage(aver);

        } catch (Exception e) {
            e.printStackTrace();
        }


        int i = hashrateMapper.insertSelective(hashrate);
        if (i<1){
            return -1;
        }
        return addSpaceHashrate(hashrate);
    }

    public int addSpaceHashrate(Hashrate hashrate){
        int x=0;
        SpaceHashrate spaceHashrate=new SpaceHashrate();

        List<UserSpaceVo> list = userSpaceMapper.listByUser(null);
        for (UserSpaceVo us:list){

            spaceHashrate.setSpaceId(us.getSpaceId());
            spaceHashrate.setSpace(us.getSpace());
            spaceHashrate.setHashId(hashrate.getId());

            spaceHashrate.setGetHashrate(hashrate.getAverage().multiply(new BigDecimal(us.getSpace())));
            x=spaceHashrateMapper.insertSelective(spaceHashrate);
        }



        return x;
    }

    @Override
    public List<Hashrate> listHashrate(Hashrate hashrate) {
        return hashrateMapper.listHashrate(hashrate);
    }
}
